package com.han.spider.cloudmeeting;

import com.han.spider.cloudmeeting.websocket.WebsocketClient;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/6/29
 * @Desc: 心跳计时器
 */
@Slf4j
public class HeartTimer implements Runnable {

    private final WebsocketClient websocketClient;
    /**
     * 到期时间,秒
     */
    private final int aliveSeconds;
    private final String userId;
    private boolean isRunning;

    public HeartTimer(WebsocketClient websocketClient, int aliveSeconds, String userId) {
        this.websocketClient = websocketClient;
        this.aliveSeconds = aliveSeconds;
        this.userId = userId;
        isRunning = true;
    }

    @Override
    public void run() {
        int id = 20;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time;
        long expireTime = System.currentTimeMillis() + aliveSeconds * 1000;
        while (isRunning && System.currentTimeMillis() < expireTime) {
            try {
                Thread.sleep(1000 * 18);
                time = simpleDateFormat.format(new Date());
                String data = "{\"id\":" + id++ + ",\"method\":\"general.keeplive\",\"params\":{\"expires\":60,\"date\":\"" + time + "\"}}";
                websocketClient.send(data);
                log.info(userId + ":" + data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info(userId + ":时间到,心跳检测停止");
        websocketClient.close();
    }

    private void close() {
        isRunning = false;
    }
}
